using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public static partial class Utility
{
    
    /// <summary>
    /// 实例类工具库
    /// </summary>
    public static partial class InstanceType
    {

        /// <summary>
        /// 获取类的占用字节长度
        /// <para>作用于拥有 [Serializable] 标记的类</para>
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="instance">类型的实例</param>
        /// <returns>类的占用字节长度</returns>
        public static long GetTypeLength<T>(T instance) where T : class
        {
            using (MemoryStream stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, instance);
                return stream.Length;
            }
        }

        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <returns></returns>
        public static T DeepClone<T>(T instance) where T:class
        {
            using (MemoryStream stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, instance);
                stream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(stream) as T;
            }
        }
    }
}
